<template>
  <a-select
    v-model="inputValue"
    :show-search="true"
    :allow-clear="true"
    placeholder="请选择或输入"
    @search="handleSearch"
    @change="handleChange"
    @blur="handleBlur"
  >
    <a-select-option
      ref="selectRef"
      v-for="item in filteredOptions"
      :key="item.id +'_'+ refreshKey"
      :value="item.value"
    >
      {{ item.label }}
    </a-select-option>
  </a-select>
</template>

<script>
export default {
    props: {
        options: {
            type: Array,
            required: true
        }
    },
  data () {
    return {
      filteredOptions: [],
      refreshKey: 0,
      inputValue: ''
    }
  },
  watch: {
    'inputValue': {
        handler (newItem) {
            if (newItem !== undefined) {
            this.filteredOptions = this.options.filter(item =>
                item.label.toLowerCase().includes(newItem?.toLowerCase() || '') || item.value.toLowerCase().includes(newItem?.toLowerCase || '')
            )
            console.info('333', this.filteredOptions)
        } else {
            console.info('444', this.filteredOptions)
            this.filteredOptions = this.options
        }
            console.info('watch', newItem, this.filteredOptions)
            this.refreshKey = Date.now() // 强制重新渲染
            // this.$nextTick(() => {
            //     this.$forceUpdate()
            // })
        },
        deep: true
    }
  },
  computed: {

  },
  methods: {
    handleFilteredOptions () {
        console.info('filtered Options', this.inputValue, this.options.filter(item => item.label.toLowerCase().includes(this.inputValue?.toLowerCase() || '')))
    },
    // 处理搜索事件，更新输入值
    handleSearch (value) {
        console.info('search', value)
      this.inputValue = value
      this.handleFilteredOptions()
    },
    // 处理选择事件，更新输入值
    handleChange (value) {
      this.inputValue = value
    },
    // 处理失焦事件，确保输入值保持
    handleBlur (e) {
      if (e) {
        this.inputValue = e
      }
    }
  }
}
</script>

<style scoped>
/* 可以根据需求自定义样式 */
</style>
